<template>
  <div>
    <div class="player" v-show="playlist.length>0">
      <transition name="normal" @enter="enter" @after-enter="afterEnter" @leave="leave" @after-leave="afterLeave">
        <div class="normal-player" v-show="fullScreen">
          <div class="background" :style="bgStyle"></div>
          <div class="top">
            <div class="back iconfont icon-toback" @click="back"></div>
            <div class="title overhide auto center xxl" v-html="currentSong.name"></div>
            <div class="subtitle xl center" v-html="currentSong.singer"></div>
          </div>
          <div class="sing-mid" @touchstart="touchStart"
          @touchmove="touchMove" @touchend="touchEnd">
            <div class="middle-l" ref="middlel">
              <div class="cd-wrapper" ref="cdWrapper">
                <div class="cd " :class="cdCls">
                  <img :src="currentSong.image" alt="" class="image">
                </div>
                <div class="word xl center">{{playingLyric}}</div>
              </div>
            </div>
            <scroll ref='lyricList' class="middle-r" :data='currentLyric&&currentLyric.lines'>
              <div class="lyric">
                <div v-if="currentLyric">
                  <p ref="lyricLine" :class="{'current':currentLineNum===index}" class="lyrictext" v-for="(line,index) in currentLyric.lines"> {{line.txt}}</p>
                </div>
              </div>
            </scroll>
          </div>
          <div class="bottom">
            <div class="center f0">
              <span class="dot" :class="{'active' : currentShow === 'cd'}"></span>
              <span class="dot" :class="{'active' : currentShow === 'lyric'}"></span>
            </div>
            <div class="progress flex middle">
              <span class="time m">{{format(currentTime)}}</span>
              <div class="cell-main">
                <Progress-bar :percent='percent' @changePercent="barChange"></Progress-bar>
              </div>
              <span class="time m right">{{format(currentSong.duration)}}</span>
            </div>
            <div class="operators flex middle">
              <div class="cell-main right" @click="changeMode">
                <i class="iconfont  playico" :class="iconMode"></i>
              </div>
              <div class="cell-main right">
                <i @click="prev" class="iconfont playico icon-shangyishou-yuanshijituantubiao"></i>
              </div>
              <div class="cell-main center">
                <i @click="togglePlay" :class="playIcon" class="iconfont paly"></i>
              </div>
              <div class="cell-main ">
                <i @click="next" class="iconfont playico icon-xiayishou-yuanshijituantubiao"></i>
              </div>
              <div class="cell-main ">
                <i @click="toggleFavorite(currentSong)" class="iconfont playico" :class="getFavoriteIcon(currentSong)">
              </i>
              </div>
            </div>
          </div>
        </div>
      </transition>
      <div class="mini-player flex middle" v-show="!fullScreen" @click="open">
        <img :class="cdCls" :src="currentSong.image" alt="" class="singico">
        <div class="cell-main">
          <div class="name l fn" v-html="currentSong.name"></div>
          <div class="singname l hui fn" v-html="currentSong.singer"></div>
        </div>
        <div class="control">
          <progress-circle :radius="32" :percent="percent">
            <i class="iconfont  playerIcon" :class="playIcon" @click.stop="togglePlay"></i>
          </progress-circle>
        </div>
        <div class="control">
          <i class="iconfont icon-list listIcon" @click.stop="showPlaylist"></i>
        </div>
      </div>
    </div>
    <playlist ref='playlist'></playlist>
    <audio :src="currentSong.url" ref="audio" @play="ready" @timeupdate="updateTime" @error="error" @ended="end"></audio>
  </div>
</template>


<script type="text/ecmascript-6">
import {mapGetters,mapMutations,mapActions} from 'vuex';
import animations from 'create-keyframe-animation';
import ProgressBar from 'base/process-bar/process-bar';
import progressCircle from 'base/progress-circle/progress-circle'
import playlist from 'components/playlist/playlist'

import {playMode} from 'common/js/config';
import Lyric from 'lyric-parser';
import scroll from 'base/scroll/scroll'
import {playerMixin} from 'common/js/mixin'
export default{
  name:'',
  mixins:[playerMixin],
  data(){
    return{
      songReady:false,
      currentTime:0,
      currentLyric:null,
      currentLineNum:0,
      currentShow:'cd',
      playingLyric:''
    }},
  computed:{
    //数据映射 获取get全屏,和播放状态
  ...mapGetters([
        'fullScreen',
        'playing',
        'currentIndex'
      ]),
  bgStyle(){
  	return `background-image:url(${this.currentSong.image})`
  },
  songname(){
   return this.currentSong.name&&this.currentSong.name.length>13?this.currentSong.name.slice(0,13):this.currentSong.name
  },
  singer(){
    return this.currentSong.singer&&this.currentSong.singer.length>13?this.currentSong.singer.slice(0,13):this.currentSong.singer
  },
  cdCls(){
    return this.playing?'play':'play pause'
  },
  playIcon(){
    return this.playing?'icon-zanting-yuanshijituantubiao':'icon-toplay'
  },
  percent(){
      return this.currentTime/this.currentSong.duration
    }
  },
  watch:{
    currentSong(newSong,oldSong){
      if(newSong.id===oldSong.id||!newSong.id){
        return
      };
      if (this.currentLyric) {
          this.currentLyric.stop()
        };
        clearTimeout(this.timer)
     this.timer=setTimeout(()=>{
      this.$refs.audio.play()
      this.getLyric()
      },1000)
    },
    playing(newplaying){
      const audio=this.$refs.audio;
      this.$nextTick(() => {
          newplaying ? audio.play() : audio.pause()
        })
    }
  },
  created(){
    this.touch={}
  },
  methods:{
    showPlaylist(){
      this.$refs.playlist.show()
    },
    back(){
      this.setFullScreen(false)
    },
    getLyric(){
      this.currentSong.getLyric().then((lyric)=>{
        if(this.currentSong.lyric!==lyric){return}
        this.currentLyric=new Lyric(lyric,this.handleLyric);
        if(this.playing){
          this.currentLyric.play()
        }
      }).catch(()=>{
        this.currentLyric = null
          this.currentLineNum = 0
          this.playingLyric = ''
      })
    },
    handleLyric({lineNum,txt}){
      this.currentLineNum=lineNum;
      if(lineNum>5){
        let lineEl=this.$refs.lyricLine[lineNum-5]
        this.$refs.lyricList.scrollToElement(lineEl,1000)
      }else{
         this.$refs.lyricList.scrollTo(0,0,1000)
      }
      this.playingLyric=txt
    },

    open(){
      this.setFullScreen(true)
    },
    ready(){
  this.songReady = true;
  this.savePlayHistory(this.currentSong)
    },
    error(){
      this.songReady = true
    },
    // 监听是否结束,结束触发,下一曲或者循环
    end(){
      if(this.mode===playMode.loop){
        this.loop()
      }else{
        this.next()
      }
    },
    loop(){
      this.$refs.audio.currentTime=0;
      this.$refs.audio.play();
      if(this.currentLyric){
        this.currentLyric.seek(0)
      }
    },
    togglePlay(){
       if(!this.songReady){
        return
      };
      this.setPlayingState(!this.playing);
      if (this.currentLyric) {
          this.currentLyric.togglePlay()
        };
    },
    prev(){
      if(!this.songReady){
        return
      };
      if (this.playlist.length === 1) {
          this.loop()
          return
        } else{
      let index=this.currentIndex+1;
       if(index===-1){
        index=this.playlist.length
      }
    this.setCurrentIndex(index)
    if(!this.playing){
        this.togglePlay()
      }
    }
    },
    next(){
       if(!this.songReady){
        return
      };
      if (this.playlist.length === 1) {
          this.loop()
        } else{
          let index = this.currentIndex + 1
          if (index === this.playlist.length) {
            index = 0
          }
          this.setCurrentIndex(index)
          if (!this.playing) {
            this.togglePlay()
          }
        }
    },
    updateTime(e){
      this.currentTime=e.target.currentTime
    },
    format(interval){
      interval=interval|0;
      const minute=interval/60|0;
      const second=this._pad(interval%60);
      return `${minute}:${second}`
    },
    _pad(num,n=2){
      let len=num.toString().length;
      while(len<n){
        num='0'+num;
        len++
      }
      return num
    },
    barChange(percent){
      const currentTime=this.currentSong.duration*percent;
      this.$refs.audio.currentTime=currentTime;
      this.$refs.audio.currentTime=this.currentSong.duration*percent;
      if(!this.playing){
        this.togglePlay()
      }
      if(this.currentLyric){
        this.currentLyric.seek(currentTime*1000)
      }
    },
    touchStart(e){
      this.touch.init=true;
      const touch=e.touches[0];
      this.touch.startX=touch.pageX;
      this.touch.startY=touch.pageY;
    },
    touchMove(e){
      if(!this.touch.init){
        return
      }
      const touch=e.touches[0];
      const deltaX=touch.pageX-this.touch.startX;
      const deltaY=touch.pageY-this.touch.startY;
      if(Math.abs(deltaY)>Math.abs(deltaX)){
        return
      }
      const left=this.currentShow==='cd'?0:-window.innerWidth;
      const offsetWidth=Math.min(Math.max(-window.innerWidth,left+deltaX),0);
      this.touch.percent=Math.abs(offsetWidth/window.innerWidth)
      this.$refs.lyricList.$el.style['transform']=`translate3d(${offsetWidth}px,0,0`;
        this.$refs.middlel.style.opacity=1-this.touch.percent;

    },
    touchEnd(e){
      let offsetWidth;
      let opacity;
      if(this.currentShow==='cd'){
        if(this.touch.percent>0.1){
          offsetWidth=-window.innerWidth;
          this.currentShow='lyric'
          opacity=0;
        }else{
          offsetWidth=0;
          opacity=1;
        }
      }else{
         if(this.touch.percent<0.9){
          offsetWidth=0;
           opacity=1;
          this.currentShow='cd'
        }else{
          offsetWidth=-window.innerWidth;
           opacity=0;
        }
      }
       this.$refs.lyricList.$el.style['transform']=`translate3d(${offsetWidth}px,0,0`;
       this.$refs.lyricList.$el.style['transitionDuration']=300;
       this.$refs.middlel.style.opacity=opacity;
    },
    enter(el,done){
      const{x,y,scale}=this._getPosAndScale();
      let animation={
        0:{
          transform:`translate3d(${x}px,${y}px,0) scale(${scale})`
        },
        60:{
          transform:`translate3d(0,0,0) scale(1.1)`
        },
        100:{
          transform:`translate3d(0,0,0) scale(1)`
        }
      };
      // 注册动画
      animations.registerAnimation({
        name:'move',
        animation,
        presets:{
          duration:400,
          easing:'linear'
        }
      });
      // 运行动画
      animations.runAnimation(this.$refs.cdWrapper,'move',done)
    },
    // 注销动画
    afterEnter(){
  animations.unregisterAnimation('move')
        this.$refs.cdWrapper.style.animation = ''
    },
    leave(el,done){
     this.$refs.cdWrapper.style.transition = 'all 0.4s'
        const {x, y, scale} = this._getPosAndScale()
        this.$refs.cdWrapper.style['transform'] = `translate3d(${x}px,${y}px,0) scale(${scale})`
        this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave(){
 this.$refs.cdWrapper.style.transition = ''
        this.$refs.cdWrapper.style['transform'] = ''
    },
    // 获取CD的位置
    _getPosAndScale(){
      const targetWidth=40;
      const paddingLeft=40;
      const paddingBottom=30;
      const paddingTop=80;
      const width=window.innerWidth*0.8;
      const scale=targetWidth/width;
      const x=-(window.innerWidth/2-paddingLeft);
      const y=window.innerHeight-paddingTop-width/2-paddingTop;
      return{x,y,scale}
    },
    ...mapMutations({
      setFullScreen:'SET_FULL_SCREEN'
    }),
    ...mapActions(
      ['savePlayHistory'
      ])
  },
  components:{ProgressBar,progressCircle,scroll,playlist}
}
</script>

<style rel="stylesheet" lang="less">
.normal-player{
 	position: fixed;
 	width: 100%;
 	top: 0;
  z-index: 5;
 	bottom: 0;
 	background-color: #222;
 }
 .background{
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
  z-index: -1;
  background-size: 100% 100%;
  opacity: 0.6;
  filter: blur(20px)
 }
 .top{
 position: relative;
 margin-bottom: 25px;
 .back{
  position: absolute;
  top: 0;
  left: 6px;
  z-index: 2;
  font-size: 24px;
  padding: 9px;
  color: #ffcd32;
 }
 .title{
    width: 70%;
    line-height: 40px;
    color: #fff;
}
.subtitle{
  line-height: 20px;
  color: #fff;
 }
}
.sing-mid{
  position: fixed;
  width: 100%;
  top:80px;
  bottom: 170px;
  white-space: nowrap;
  font-size: 0;
  .middle-l{
    display: inline-block;
    vertical-align: top;
    position: relative;
    width: 100%;
    height: 0;
    padding-top: 80%;
  }
  .cd-wrapper{
    position: absolute;
    left: 10%;
    top: 0;
    width: 80%;
    height: 100%;
  }
  .cd{
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    border: 10px solid rgba(255,255,255,0.1);
    border-radius: 50%;
  }
  .cd.play{
       animation: rotate 20s linear infinite;
    }
    .cd.pause{
      animation-play-state: paused
    }
  .image{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
}
  .word{
    width: 80%;
    margin: 30px auto 0;
    overflow: hidden;
    line-height: 20px;
    color: rgba(255,255,255,0.8);
  }
}
.bottom{
    position: absolute;
    bottom: 50px;
    width: 100%;
    color: #ffcd32;
    .playico{
      font-size: 40px;
    }
    .paly{
      font-size: 50px;
    }
}
.mini-player{
  position: absolute;
  bottom: 0;
  z-index: 5;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background-color: #333;
  .singico{
    width: 40px;
    height: 40px;
    border-radius: 50%;
    padding: 0 10px 0 20px;
  }
  .playerIcon{
    font-size: 29px;
    position: absolute;
    top: -8.5px;
    left: 1.5px;
    color: rgba(255,205,49,0.5);
  }
  .listIcon{
        font-size: 30px;
         color:#ffcd32;
  }
}
 .normal-enter-active,.normal-leave-active{
 transition: all 0.4s;
   .top, .bottom{
    transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
   }
 }
.normal-enter, .normal-leave-to{
  opacity: 0;
  .top{
  transform: translate3d(0, -100 px, 0);
  }
  .bottom{
    transform: translate3d(0, 100 px, 0)
  }
}

  @keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.progress{
  width: 80%;
  margin: 0 auto;
  padding: 10px 0;
  .time{
    color: #fff;
    flex:0 0 30px;
    line-height: 30px;
  }
}
 .control{
    -webkit-box-flex: 0;
    -ms-flex: 0 0 30px;
    flex: 0 0 30px;
    width: 30px;
    padding: 0 10px;
 }
.middle-r{
     display: inline-block;
    vertical-align: top;
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.lyric{
    width: 80%;
    margin: 0 auto;
    overflow: hidden;
    text-align: center;
    .current{
      color: #fff;
    }
}
.lyrictext{
    line-height: 32px;
    color: rgba(255,255,255,0.5);
    font-size: 14px;
}
.dot{
      display: inline-block;
    vertical-align: middle;
    margin: 0 4px;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: rgba(255,255,255,0.5);
    &.active{
    width: 20px;
    border-radius: 5px;
    background: rgba(255,255,255,0.8);
    }
}
</style>
